package com.lottery.shadowbd.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.lottery.shadowbd.R;
import com.lottery.shadowbd.callback.OnDownloadListener;
import com.lottery.shadowbd.io.api.MainApiIO;
import com.lottery.shadowbd.support.Constant;
import com.lottery.shadowbd.utils.FileUtil;
import com.lottery.shadowbd.utils.LogUtils;
import com.lottery.shadowbd.utils.ToastUtil;

import java.io.File;

/**
 * 输入金额dialog
 *
 * @author han 2017-04-26
 */
public class DownLoadingDialog extends DialogFragment {

    private final int DOWN_OK = 0x01;
    private final int DOWN_UPDATE = 0x02;
    private final int DOWN_ERROR = 0x03;

    private Context mContext;

    private Dialog dialog;

    //关闭
    private NumberProgressBar numProgressBar;

    private DownLoadingCallBack mDownLoadingCallBack;

    private int updateCount = 0;
    //更新步数， 大于2步更新一次
    private int down_step = 2;
    //总进度
    private long totals;
    //当前进度
    private long currents;

    private String apkName;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case DOWN_OK:
                    mDownLoadingCallBack.onDownLoadingSucess(apkName);
                    break;
                case DOWN_UPDATE:
                    int progress = (int) (currents * 1.0f / totals * 100);
                    setNumProgress(progress);
                    mDownLoadingCallBack.onDownLoading(progress);
                    break;
                case DOWN_ERROR:
                    dismiss();
                    mDownLoadingCallBack.onDownLoadingFail("下载出错!");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        mContext = getActivity();

        // 定义Dialog布局和参数
        dialog = new Dialog(mContext, R.style.DowlLoadingDialogStyle);

        // 获取Dialog布局
        View view = LayoutInflater.from(mContext).inflate(
                R.layout.dialog_downloading, null);

        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        dialog.setContentView(view);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);

        numProgressBar = (NumberProgressBar) view.findViewById(R.id.numProgressBar);

        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.LEFT | Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();

        lp.gravity = Gravity.CENTER; // 居中
        lp.dimAmount = 0.5f;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平

        dialogWindow.setAttributes(lp);
        dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        //禁止返回按键
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    return true;
                }
                return false;
            }
        });

        return dialog;
    }

    public void setmDownLoadingCallBack(DownLoadingCallBack mDownLoadingCallBack) {
        this.mDownLoadingCallBack = mDownLoadingCallBack;
    }

    public void setNumProgress(int num) {
        if (numProgressBar != null) {
            numProgressBar.setProgress(num);
        }
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        Fragment mFragment = manager.findFragmentByTag(tag);
        //防止java.lang.IllegalStateException: Fragment already added
        if (mFragment == null || !mFragment.isAdded()) {
            super.show(manager, tag);
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
    }

    public void downloadFile(String downUrl) {
        if (downUrl == null || "".equals(downUrl)) {
            ToastUtil.showShort(mContext, "下载地址出错!");
            return;
        }
        if (!FileUtil.hasSdcard()) {//没有sd卡
            ToastUtil.showShort(mContext, "没有插入SD卡!");
            return;
        }

        if (!FileUtil.checkExternalStorageCanWrite()) {//没有SD卡读取权限
            ToastUtil.showShort(mContext, "没有内存卡读取权限!");
            return;
        }

        if (FileUtil.getSDFreeSize() < 60) {//sd卡剩余空间不足
            ToastUtil.showShort(mContext, "剩余空间不足!");
            return;
        }

        FileUtil.deleteAllFiles(new File(Constant.RootApkPath));

        if (!FileUtil.isExistDir(Constant.RootApkPath)) {//创建文件失败
            ToastUtil.showShort(mContext, "创建文件失败!");
            return;
        }

        apkName = System.currentTimeMillis() + ".apk";

        /**
         * 下载文件方法
         * @param url 下载文件的url
         * @param target 下载文件的路径
         */
        MainApiIO.getInstance().postDownLoad(downUrl, Constant.RootApkPath, apkName, new OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                mHandler.sendEmptyMessage(DOWN_OK);
            }

            @Override
            public void onDownloading(long total, long current) {
                if (current == 0 || (current * 100) / total >= updateCount) {
                    updateCount += down_step;

                    totals = total;
                    currents = current;

                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                }
            }

            @Override
            public void onDownloadFailed(Exception e) {
                mHandler.sendEmptyMessage(DOWN_ERROR);
                LogUtils.e("e===" + e.toString());
            }
        });
    }

    public interface DownLoadingCallBack {
        void onDownLoadingSucess(String apkName);

        void onDownLoadingFail(String error);

        void onDownLoading(int num);
    }

    public void onDialogDestroy() {
        if(mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }
}
